
;(function(doc){
    var Waterfall = function(warp,opt){
        this.oWarp = doc.querySelector(warp);
        this.column = opt.column;
        this.gap = opt.gap;
        //每个盒子的宽度
        this.itemW =(this.oWarp.offsetWidth-(this.column-1)*this.gap)/this.column+'px';
        //每列高度的arr
        this.heightArr = [];
    };

    Waterfall.prototype = {
        init(){
            this.getImgData();
        },
        bindEvent(){

        },
        scrollToBottom(){

        },
        getImgData(){
            var _this = this;
            $.ajax({
                url:"./data.json",
                type:"get",
                success:function(res){
                    _this.renderList(res);
                }
            })
        },
        renderList(data){
            var _this = this,
                minInd = -1,
                oItems = null;

            data.forEach(function(item,index){
                var oItem = doc.createElement("div"),
                    oImg = new Image(),
                    itemLeft = (parseInt(_this.itemW) + _this.gap)*(index % _this.column),
                    itemH = parseInt(_this.itemW) / item.width * item.height;

                oItem.className = "wf-item";
                oItem.style.width = _this.itemW;
                oItem.style.height = itemH +'px';
                oImg.src = item.img;

                if(index < _this.column){
                    oItem.style.top = '0';
                    oItem.style.left = itemLeft + 'px';
                    _this.heightArr.push(itemH + _this.gap);
                }else{
                    minInd = arrMinInd(_this.heightArr);
                    oItem.style.left = (parseInt(_this.itemW) + _this.gap)*minInd + 'px';

                    oItem.style.top = (_this.heightArr[minInd]) + 'px';
                    _this.heightArr[minInd] += (itemH + _this.gap);
                }

                oItem.appendChild(oImg);
                _this.oWarp.appendChild(oItem);

            });
        }
    };

    function arrMinInd(arr){
        return [].indexOf.call(arr,Math.min.apply(null,arr));
    }

    window.Waterfall = Waterfall
})(document);
